import { create, update, remove, query } from '../../../framework/service/index';
import { ToastTips } from '../../../common/toastTips/tosat';
import token from '../../../framework/utils/token';

const delay = timeout => {
  return new Promise(resolve => {
    setTimeout(resolve, timeout);
  });
};

export default {

  namespace: 'login',

  state: {
    info:''
  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
      history.listen(location => {
        if(location.pathname === '/login') {
          dispatch({
            type: 'postLogin',
          })
        }
      })
    },
  },

  effects: {
    *postLogin({ payload }, { call, put, select }){
      console.log('登录');
      const { code, data, message } = yield call(create, '/api/oauth/app/login', payload.data);
      // console.log('code', JSON.stringify(code));
      // console.log('data', JSON.stringify(data));
      // console.log('message', JSON.stringify(message));
      if (code === 200) {
        if(!payload.data.isRegister){
          ToastTips("登录成功，正在跳转",1.5,null,false);
        }
        token.save(data.accessToken);
        yield call(delay, 1000);
        // console.log('aasd',window.MC.hostPrefix);
        window.location.href = window.MC.hostPrefix;
      }else{
        ToastTips('登录失败，账号或密码错误', 2000, null);
      }
    }
  },

  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },
  },

};
